package com.ideaaedi.springcloud.jd.gateway.config;

import com.google.common.collect.Lists;
import com.ideaaedi.springcloud.jd.commonds.constant.BaseConstant;
import com.ideaaedi.springcloud.jd.commonds.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * (non-javadoc)
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2021.0.1.A
 */
@Slf4j
@Configuration
public class GlobalFilterConfig {
    
    /**
     * 开启调用链路追踪功能的话，就无需手动处理traceId了
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter traceIdInitFilter() {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String traceId = CommonUtil.getTraceId(request.getURI().getPath(), request.getHeaders().getFirst(BaseConstant.TRACE_ID));
            log.info("Init traceId to request-header -> [{}].", traceId);
            ServerHttpRequest modifiedRequest = exchange.getRequest().mutate()
                    .headers(httpHeaders -> {
                                httpHeaders.put(BaseConstant.IF_CROSS_MICRO_SERVICE_REQUEST, Lists.newArrayList(Boolean.FALSE.toString()));
                                httpHeaders.put(BaseConstant.TRACE_ID, Lists.newArrayList(traceId));
                            }
                    ).build();
            return chain.filter(exchange.mutate().request(modifiedRequest).build());
        };
    }
}
